package org.meb.conquest.web;

import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.meb.conquest.web.auth.WebUser;

public class AccessFilter implements Filter {

	@Inject
	private WebUser webUser;

	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		// User user = (User)
		// request.getSession().getAttribute(TwitterAuthServlet.SIGNED_IN_USER);
		if (webUser.isSignedIn()) {
			chain.doFilter(request, response);
		} else {
			StringBuilder origin = new StringBuilder();
			origin.append(request.getRequestURI());
			if (request.getQueryString() != null) {
				origin.append("/").append(request.getQueryString());
			}
			response.sendRedirect(request.getContextPath() + "/auth/twitter?origin=" + origin);
		}
	}
}
